﻿using Grow.Domain.EventBus;
using Grow.Domain.EventBus.CreateEventBus;
using Grow.EventBus.Cap.SubscriberDomainEvents;
using Grow.Module.Options;
using Grow.Module.Service;
using Microsoft.Extensions.DependencyInjection;

namespace Grow.EventBus.Cap.Kafka.CreateEventBus
{
    public class CreateEventBusBuilder : ICreateEventBusBuilder
    {
        private readonly IServiceContainer _serviceContainer;

        public CreateEventBusBuilder(IServiceContainer serviceContainer)
        {
            _serviceContainer = serviceContainer;
        }
        public ICreateEventBusBuilder AddEventBusOptions(Action<IOptionsBind, DomainEventBusOptions> eventBusOptionsAction)
        {
            _serviceContainer.OptionsManager.AddOptions<DomainEventBusOptions>(a =>
            {
                eventBusOptionsAction(_serviceContainer.OptionsManager.GetOptionsBind(), a);
            });
            return this;
        }
        public ICreateEventBusBuilder AddDomainEvent<TDomainEvent>(Action<IOptionsBind, DomainEventOptions> eventOptionsAction) where TDomainEvent : IDomainEvent
        {
            _serviceContainer.OptionsManager.AddOptions<DomainEventOptions>(typeof(TDomainEvent).FullName!, a =>
            {
                eventOptionsAction(_serviceContainer.OptionsManager.GetOptionsBind(), a);
            });
            return this;
        }

        public ICreateEventBusBuilder AddDomainEventHandler<TDomainEventHandler, TDomainEvent>(Action<IOptionsBind, DomainEventHandlerOptions> eventHandlerOptionsAction)
            where TDomainEventHandler : class, IDomainEventHandler<TDomainEvent>
            where TDomainEvent : IDomainEvent
        {
            _serviceContainer.OptionsManager.AddOptions<DomainEventHandlerOptions>(typeof(TDomainEventHandler).FullName!, a =>
            {
                eventHandlerOptionsAction(_serviceContainer.OptionsManager.GetOptionsBind(), a);
            });

            _serviceContainer.ServiceCollection.AddTransient<TDomainEventHandler>();
            _serviceContainer.ServiceCollection.AddSingleton<ISubscriberDomainEvent, SubscriberDomainEvent<TDomainEventHandler, TDomainEvent>>();
            return this;
        }

       
    }
}
